/**
 * 
 */
package net.looker.monitor.parser;

import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.looker.data.Media;
import net.looker.data.News;
import net.looker.util.Html;
import net.looker.util.URLUtils;

/**
 * 图片解析器
 * @author solosky
 *
 */
public class ImageParser extends Parser
{

	/**构造函数
	 * @param news
	 */
	public ImageParser(News news) 
	{
		super(news);
	}


	/* (non-Javadoc)
	 * @see net.looker.site.category.parser.Parser#parse()
	 */
	@Override
	public boolean parse()
	{
		boolean matched = false;
		String imgTagRegxp = "<img (.*?)>";
		Pattern pt = Pattern.compile(imgTagRegxp,Pattern.CASE_INSENSITIVE);	//不区分大小写
		Matcher mc = pt.matcher(news.getContent());
		while (mc.find())
		{
			parseImgTag(mc.group(0));
			matched = true;
		}
		return matched;
	}
	
	
	/**
	 * 解析出Img标签
	 */
	private void parseImgTag(String imgTag)
	{
		Logger logger = Logger.getLogger("looker");
		
		Media img = new Media();
		//解析图片地址
		String srcRegxp = "src=['\"](.*?)['\"]";
		Pattern pt = Pattern.compile(srcRegxp, Pattern.CASE_INSENSITIVE);
		Matcher mc = pt.matcher(imgTag);
		if (mc.find())
		{
			img.setUrl(URLUtils.real(mc.group(1), news.getUrl()));
			img.setOriginal(mc.group(1));
		}
		//尝试解析图片说明
		String titleRegxp ="alt=['\"](.*?)['\"]";
		 pt = Pattern.compile(srcRegxp, Pattern.CASE_INSENSITIVE);
		 mc = pt.matcher(titleRegxp);
		if (mc.find())
			img.setTitle(mc.group(1));
		else
			img.setTitle(news.getTitle());
		
		//添加至列表
		addMedia(img);
		
		logger.info("成功解析图片:"+img.getUrl());
	}

}
